/**
 * 所属节点：货位编辑
 * 创建人：zm
 * 创建时间：2020年10月29日
 * 最后修改人：zm
 */
cb.define(process.env.__DOMAINKEY__, function () {
  let GDGY01_dxq_location_VM_Extend = {
    doAction: function (name, viewModel) {
      if (this[name]) this[name](viewModel);
    },
    init: function (viewModel) {
      let tenantID = viewModel.getAppContext().tenant.tenantId;
      const qianzhui = "/gdgy/pc/isv2";
      viewModel.get("locationName") &&
        viewModel.get("locationName").on("afterValueChange", function (data) {
          // 名称--值改变后
          let locationName = viewModel.get("locationName");
          let nodeName = viewModel.get("name");
          nodeName.setValue(locationName.getValue());
          nodeName.setReadOnly(false);
          nodeName.setState("bCanModify", false);
          // console.log("locationName" , locationName.getValue(), nodeName.getValue(), data);
        });

      viewModel.get("button12og") &&
        viewModel.get("button12og").on("click", function (data) {
          //发签--单击

          let result = getLableCode("B01");
          let RFIDCode = viewModel.get("RFIDCode");
          RFIDCode.setValue(result);
          RFIDCode.setState("bCanModify", false);
          let val = viewModel.get("RFIDCode").getValue();
          if (!cb.utils.isEmpty(val)) {
            window.location.href = "DXCFMSG://" + val;
          } else {
            cb.utils.alert("发签识别，请重试");
            return false;
          }
        });

      //生成标签
      function getLableCode(prefix) {
        let day = new Date().myFormat("yyyyMMdd");
        let time = new Date().myFormat("hhmmssfff");
        let strRandomNum = randomNum(1000, 9999);
        let res = day + appfixInteger(time, 9) + strRandomNum;

        return prefix + res;
      }
      function randomNum(minNum, maxNum) {
        switch (arguments.length) {
          case 1:
            return parseInt(Math.random() * minNum + 1, 10);
            break;
          case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            break;
          default:
            return 0;
            break;
        }
      }
      //数字前补零
      function prefixInteger(num, length) {
        return (num / Math.pow(10, length)).toFixed(length).substr(2);
      }
      //数字后补零
      function appfixInteger(num, length) {
        if ((num + "").length < length) return appfixInteger(num + "0", length);
        else if ((num + "").length > length) return (num + "").substr(0, length);
        else return num;
      }

      Date.prototype.myFormat = function (format) {
        var o = {
          "M+": this.getMonth() + 1, // month
          "d+": this.getDate(), // day
          "h+": this.getHours(), // hour
          "m+": this.getMinutes(), // minute
          "s+": this.getSeconds(), // second
          "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
          S: this.getMilliseconds(),
          "f+": this.getMilliseconds(),
          // millisecond
        };
        if (/(y+)/.test(format)) {
          format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        } else if (new RegExp("(f+)").test(format)) {
          var _minSeconds = this.getMilliseconds() + "";
          format = format.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? ("0" + _minSeconds).substr(("" + _minSeconds).length)
              : RegExp.$1.length == 2
                ? ("00" + _minSeconds).substr(("" + _minSeconds).length)
                : ("000" + _minSeconds).substr(("" + _minSeconds).length)
          );
        }
        for (var k in o) {
          if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
          }
        }
        return format;
      };

      viewModel.on("customInit", function (data) {
        //智能货位--页面初始化

        // 智能货位详情--页面初始化
        // console.log("============[智能货位]");

        //卡片页面数据加载完成
        viewModel.on("afterLoadData", function () {
          // console.log("[afterLoadData]", data);

          //监听父级-上级名称参照
          viewModel.get("item70dk_name").on("afterValueChange", function (data) {
            if (data.value !== null) {
              //层级
              viewModel.get("level").setValue(parseInt(data.value.level) + 1);
            }
          });
          let pageType = data.originalParams.mode;

          let huoweiNow = viewModel.getCache("parentViewModel").selectedHuowei;
          // console.log(huoweiNow, huoweiNow.length);

          //RFID编码
          let RFIDCode = viewModel.get("RFIDCode");
          RFIDCode.setDisabled(true);
          RFIDCode.setState("bCanModify", false);
          //节点标题
          let nodeName = viewModel.get("name");
          nodeName.setDisabled(true);
          nodeName.setState("bCanModify", false);

          // console.log("[]"+pageType);
          if (pageType == "edit") {
            // console.log("[edit]");
            UIInitData();
          } else if (pageType == "add") {
            //货位的RFID编码信息，进入页面赋值
            // var level = viewModel.get('level').getValue();
            // if(level === 3){
            //   let result = getLableCode("B01");
            //   let RFIDCode = viewModel.get('RFIDCode');
            //   RFIDCode.setValue(result);
            // }
            // RFIDCode.setState("bCanModify", false);
          } else {
            UIInitData();
            // console.log("[UIInitData-show]");
          }
        });

        function UIInitData() {
          let billData = data.originalParams.rowData;
          // console.log("[UIInitData]", billData);
          //上级名称-非参照
          let parentNameObj = viewModel.get("parentName");
          //仓库ID-非参照
          let warehouseID = viewModel.get("warehouseID").getValue();
          // console.log(warehouseID, parentNameObj);
          viewModel.get("locationCode").setDisabled(false);
          viewModel.get("locationName").setDisabled(false);
          viewModel.get("btnSaveAndAdd").setDisabled(false);
          viewModel.get("btnSave").setDisabled(false);
          //仓库-参照
          let cangkuUI = viewModel.get("item39td_name");
          //仓库ID-参照框ID
          viewModel.get("item39td").setValue(billData.warehouseID);
          cangkuUI.setDisabled(true);
          cangkuUI.setState("bCanModify", false);
          cangkuUI.setValue(billData.warehouseName);
          //上级名称-参照
          let parentUI = viewModel.get("item70dk_name");
          //console.log(parentUI);
          parentUI.setDisabled(true);
          parentUI.setState("bCanModify", false);
          if (billData.level == 1) {
            parentUI.setValue(billData.warehouseName);
            //上级名称-参照框ID
            viewModel.get("item70dk").setValue(billData.warehouseID);
            viewModel.get("parent").setValue(billData.warehouseID);
            viewModel.get("parentName").setValue(billData.warehouseName);
          } else {
            parentUI.setValue(billData.parentName);
            //上级名称-参照框ID
            viewModel.get("item70dk").setValue(billData.parent);
            viewModel.get("parent").setValue(billData.parent);
            viewModel.get("parentName").setValue(billData.parentName);
          }
          viewModel.get("warehouseID").setValue(billData.warehouseID);
          viewModel.get("warehouseName").setValue(billData.warehouseName);
          viewModel.get("warehouseCode").setValue(billData.warehouseCode);
          viewModel.get("level").setValue(billData.level);

          //是否末级
          viewModel.get("ifEnd").setValue(billData.ifEnd);
        }

        viewModel.on("beforeSave", function (args) {
          // console.log("beforeSave-------------------------------------------");
          //事件发生之前，可以进行特色化处理，以此为例，可以进行保存之前数据校验，通过return true;否则return false;
          //console.log('beforeSave',args);
          // 获取单个数据的内容
          const innerdata = JSON.parse(args.data.data);
          //console.log(innerdata);

          let pageType = data.originalParams.mode;
          let parentParams = viewModel.getCache("parentViewModel");
          //console.log(pageType, parentParams, innerdata);

          let parentId = viewModel.get("parent").getValue();
          let locationCode = viewModel.get("locationCode").getValue();
          // console.log(parentId);
          if (typeof parentId == "undefined") {
            cb.utils.alert("操作异常，请刷新重试");
            return false;
          }
          let level = innerdata.level;
          if (level > 3) {
            cb.utils.alert('仅支持自建 "区域-货架-货位" 三级数据! ');
            return false;
          }
          //组织信息去掉
          //let orgid = innerdata.org_id;
          //let curOrgid = viewModel.get('org_id').getValue();
          //if (curOrgid != orgid){
          //    cb.utils.alert("组织信息和父级不一致! ");
          //    return false;
          //}
          // console.log(JSON.stringify(pageType))
          if (pageType == "add") {
            //2054080273138057219 == GDGY01.Location.CLocationCode 验证当前级别数据唯一
            // let locationCodeCheck = cb.rest.invokeFunction(
            //   "GDGY01.Location.CLocationCode",
            //   { parentId: parentId, locationCode: locationCode },
            //   function (err, res) {},
            //   viewModel,
            //   { async: false }
            // );
            // //console.log(pageType, locationCodeCheck)
            // const rstParent = locationCodeCheck.result.rstParent;
            // const res = locationCodeCheck.result.rst;
            // if (res.length > 0) {
            //   cb.utils.alert("货位编码已经存在，请重新输入货位编码", "error");
            //   return false;
            // }

            /**
             * 张明迁移
             */
            const url =
              qianzhui +
              "/location/GetList?locationID=" +
              parentId +
              "&locationCode=" +
              locationCode +
              "&tenant_id=" +
              tenantID +
              "&level=" +
              level;
            const proxy = viewModel.setProxy({
              isLocationcodeExist: {
                url: url,
                method: "GET",
                options: {
                  mask: false,
                },
              },
            });
            const locationExist = proxy.isLocationcodeExistSync({});
            if (locationExist.dataList && locationExist.dataList.length > 0) {
              cb.utils.alert("货位编码已经存在，请重新输入货位编码", "error");
              return false;
            }

            //父级isEnd更新
            // let editParentEnd = cb.rest.invokeFunction(
            //   "GDGY01.Location.EditParentEnd",
            //   { id: parentId, isEnd: "0" },
            //   function (err, res) {},
            //   viewModel,
            //   { async: false }
            // );
            // if (editParentEnd.result.status !== 1) {
            //   cb.utils.alert("操作失败，原因：" + objJSON.message, "error");
            //   return false;
            // }

            /**
             * 张明迁移
             */

            const url_locationend =
              qianzhui + "/location/EditLocationEnd?isEnd=" + "0" + "&id=" + parentId + "&tenant_id=" + tenantID;
            const proxy_locationend = viewModel.setProxy({
              EditParentEnd: {
                url: url_locationend,
                method: "GET",
              },
            });
            proxy_locationend.EditParentEnd({}, function (err, res) {
              if (err) {
                cb.utils.alert(err.message);
              } else {
                //TODO:判断依据没有确定
                if (res.status !== 1) {
                  cb.utils.alert("操作失败，原因：" + objJSON.message, "error");
                  return false;
                }
              }
            });
          }

          // console.log("beforeSave End-------------------------------------------");
        });

        viewModel.on("afterSave", function (params) {
          // console.log('afterSave',params);
          //事件发生之后，可以进行保存成功以后的特色化需求
          // console.log("afterSave-------------------------------------------");
          viewModel.getCache("parentViewModel").flagBack = true;
          // console.log("afterSave End-------------------------------------------");
        });

        // 删除前
        viewModel.on("beforeDelete", function (args) {
          cb.utils.alert("操作不支持!", "error");
          return false;
        });
      });
    },
  };
  try {
    module.exports = GDGY01_dxq_location_VM_Extend;
  } catch (error) {}
  return GDGY01_dxq_location_VM_Extend;
});
